import cantools
FT_CAN = 0                      # CAN帧
FT_CANFD = 1                    # CANFD帧

class DBCParser:
    def __init__(self, dbc_file_path):
        self.db = cantools.database.load_file(dbc_file_path)
    
    def parse_signals(self, frame_type: int = FT_CAN):
        signals_list = []
        
        # 遍历所有消息
        for message in self.db.messages:
            # 获取消息基本信息
            message_id = message.frame_id
            is_fd = message.is_fd
            cycle_time = message.cycle_time if message.cycle_time else 0
            length = message.length  # 获取实际消息长度
            
            # 创建信号初始值字典
            signal_values = {}
            if message.signals:
                for signal in message.signals:
                    if signal.initial is not None:
                        signal_values[signal.name] = signal.initial
            
            # 使用Message的encode方法编码整个消息
            encoded_data = message.encode(signal_values) if signal_values else bytearray(length)
            
            # 将字节数组转换为整数列表
            data = list(encoded_data)
            
            # 添加到信号列表
            signals_list.append({
                'id': message_id,
                'data': data,
                'cycle_ms': cycle_time,
                'is_canfd': frame_type == FT_CANFD,
            })
        
        return signals_list

# 示例用法
if __name__ == "__main__":
    dbc_file = "E:/project/testscript/xiaomi/data/Kunlun_ETC_BodyCANFD_240501.dbc"
    parser = DBCParser(dbc_file)
    signals = parser.parse_signals()
    for signal in signals:
        hex_data = ' '.join(f'{x:02X}' for x in signal['DATA'])
        print(f"ID: 0x{signal['id']:03X}, DATA: {hex_data}, Cycle: {signal['cycle']}ms, CANFD: {signal['CANFD']}")